package com.gitee.wsl.doc.prosemirror.model.fragment.ext

import com.gitee.wsl.doc.prosemirror.exception.RangeError
import com.gitee.wsl.doc.prosemirror.model.fragment.Fragment

fun Fragment.removeRange(from: Int, to: Int): Fragment {
    val content = this
    val (index, offset) = content.findIndex(from).run { index to offset }
    val child = content.maybeChild(index)
    val (indexTo, offsetTo) = content.findIndex(to).run { this.index to this.offset }
    if (offset == from || child!!.isText) {
        if (offsetTo != to && !content.child(indexTo).isText) throw RangeError("Removing non-flat range")
        return content.cut(0, from).append(content.cut(to))
    }
    if (index != indexTo) throw RangeError("Removing non-flat range")
    return content.replaceChild(index, child.copy(child.content.removeRange( from - offset - 1, to - offset - 1)))
}